package jgo.plugins.template;

import java.io.IOException;
import java.io.StringWriter;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import jgo.JGo;
import jgo.plugin.TemplateEnginePlugin;

public class FreemarkerTemplatePlugin extends TemplateEnginePlugin {
    private Configuration configuration;

    @Override
    public void init(JGo jgo) {
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        // 设置模板加载器，这里假设模板文件在 classpath 的 templates 目录下
        configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "templates");
    }

    @Override
    public String render(String templateName, Object data) {
        try {
            Template template = configuration.getTemplate(templateName);
            StringWriter writer = new StringWriter();
            template.process(data, writer);
            return writer.toString();
        } catch (IOException | TemplateException e) {
            throw new RuntimeException("Error rendering template: " + templateName, e);
        }
    }
}